package com.io.zxing

import android.graphics.Bitmap
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import com.io.commonlib.helper.LogHelper
import com.journeyapps.barcodescanner.BarcodeEncoder

/**
 * Description:
 * 2021-05-11 16:07
 * @author LiuMin
 */
object ZXingHelper {
    private val TAG = ZXingHelper::class.java.simpleName

    /**
     * 根据传入的【content】-内容，【width】-二维码图片的宽度，【height】-二维码图片的高度
     * 获取二维码图片
     */
    fun getQRCodeBitmap(content: String, width: Int, height: Int): Bitmap? {
        var bitmap: Bitmap? = null
        try {
            val hashMap = HashMap<EncodeHintType, Any>()
            hashMap.put(EncodeHintType.MARGIN, 0)
            bitmap = BarcodeEncoder().encodeBitmap(
                content,
                BarcodeFormat.QR_CODE,
                width,
                height,
                hashMap
            )
        } catch (e: Exception) {
            LogHelper.e(TAG, "getQRCodeBitmap--Exception:${e.message}")
        }
        return bitmap
    }

    /**
     * 根据传入的【content】-内容，【width】-二维码图片的宽度，【height】-二维码图片的高度
     * 【charset】-字符集，【level】-容错率，容错级别越高识别的越慢
     * 获取二维码图片
     */
    fun getQRCodeBitmapWithExtra(
        content: String,
        width: Int,
        height: Int,
        charset: String?,
        level: ZXingErrorCorrectionLevel?
    ): Bitmap? {
        var bitmap: Bitmap? = null
        try {
            val hashMap = HashMap<EncodeHintType, Any>()
            hashMap.put(EncodeHintType.MARGIN, 0)
            if (charset != null || level != null) {
                charset?.let {
                    hashMap.put(EncodeHintType.CHARACTER_SET, charset)
                }
                level?.let {
                    val levelNew = getErrorCorrectionLevel(level)
                    hashMap.put(EncodeHintType.ERROR_CORRECTION, levelNew)
                }
            }
            bitmap =
                BarcodeEncoder().encodeBitmap(
                    content,
                    BarcodeFormat.QR_CODE,
                    width,
                    height,
                    hashMap
                )
        } catch (e: Exception) {
            LogHelper.e(TAG, "getQRCodeBitmap--Exception:${e.message}")
        }
        return bitmap
    }

    private fun getErrorCorrectionLevel(sourceLevel: ZXingErrorCorrectionLevel): ErrorCorrectionLevel {
        when (sourceLevel) {
            ZXingErrorCorrectionLevel.L ->
                return ErrorCorrectionLevel.L
            ZXingErrorCorrectionLevel.M ->
                return ErrorCorrectionLevel.M
            ZXingErrorCorrectionLevel.Q ->
                return ErrorCorrectionLevel.Q
            ZXingErrorCorrectionLevel.H ->
                return ErrorCorrectionLevel.H
            else ->
                return ErrorCorrectionLevel.L
        }
    }

}